package org.zn.note.designpattern;

import java.util.ArrayList;
import java.util.List;

/**
 * 传输对象模式（Transfer Object Pattern）
 * <p>
 * 业务对象（Business Object） - 为传输对象填充数据的业务服务。
 * 传输对象（Transfer Object） - 简单的 POJO，只有设置/获取属性的方法。
 * 客户端（Client） - 客户端可以发送请求或者发送传输对象到业务对象。
 */
public class Pattern33_TransferObject {

    public static void main(String[] args) {
        StudentBO studentBusinessObject = new StudentBO();

        //输出所有的学生
        for (StudentVO student : studentBusinessObject.getAllStudents()) {
            System.out.println("Student: [RollNo : "
                    + student.getRollNo() + ", Name : " + student.getName() + " ]");
        }

        //更新学生
        StudentVO student = studentBusinessObject.getAllStudents().get(0);
        student.setName("Michael");
        studentBusinessObject.updateStudent(student);

        //获取学生
        studentBusinessObject.getStudent(0);
        System.out.println("Student: [RollNo : "
                + student.getRollNo() + ", Name : " + student.getName() + " ]");
    }

    private static class StudentBO {

        //列表是当作一个数据库
        List<StudentVO> students;

        StudentBO() {
            students = new ArrayList<StudentVO>();
            StudentVO student1 = new StudentVO("Robert", 0);
            StudentVO student2 = new StudentVO("John", 1);
            students.add(student1);
            students.add(student2);
        }

        void deleteStudent(StudentVO student) {
            students.remove(student.getRollNo());
            System.out.println("Student: Roll No "
                    + student.getRollNo() + ", deleted from database");
        }

        //从数据库中检索学生名单
        List<StudentVO> getAllStudents() {
            return students;
        }

        StudentVO getStudent(int rollNo) {
            return students.get(rollNo);
        }

        void updateStudent(StudentVO student) {
            students.get(student.getRollNo()).setName(student.getName());
            System.out.println("Student: Roll No "
                    + student.getRollNo() + ", updated in the database");
        }
    }

    private static class StudentVO {
        private String name;
        private int rollNo;

        StudentVO(String name, int rollNo) {
            this.name = name;
            this.rollNo = rollNo;
        }

        String getName() {
            return name;
        }

        void setName(String name) {
            this.name = name;
        }

        int getRollNo() {
            return rollNo;
        }

        void setRollNo(int rollNo) {
            this.rollNo = rollNo;
        }
    }
}
